package com.study.webapp.lock;

import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriterLockTest {

	public static void main(String[] args) {
		ReentrantReadWriterLockTest t = new ReentrantReadWriterLockTest();
		ReentrantReadWriterLockTest.model m = t.new model();
		for (int i = 0; i < 3; i++) {
			new Thread() {
				public void run() {
					m.get();
				}
			}.start();
		}

		for (int i = 0; i < 3; i++) {
			new Thread() {
				public void run() {
					m.put(new Random().nextInt(10000));
				}
			}.start();
		}
	}

	class model {
		private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
		private Object data = null;

		public void get() {
			lock.readLock().lock();
			System.out.println(Thread.currentThread().getName() + ">>读锁");
			try {
				Thread.sleep((long) (Math.random() * 1000));
			} catch (Exception e) {

			}
			System.out.println(Thread.currentThread().getName() + ">>读锁>>" + data);
			lock.readLock().unlock();
		}

		public void put(Object data) {
			lock.writeLock().lock();
			System.out.println(Thread.currentThread().getName() + ">>>>写锁");
			try {
				Thread.sleep((long) (Math.random() * 1000));
			} catch (Exception e) {

			}
			this.data = data;
			System.out.println(Thread.currentThread().getName() + ">>写锁>>" + data);
			lock.writeLock().unlock();
		}
	}
}
